package net.csdn.business.framework.async.config.factory;

import io.opentracing.Scope;
import io.opentracing.Span;
import io.opentracing.Tracer;
import io.opentracing.util.GlobalTracer;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ThreadFactory;


/**
 * @ClassName DiscussFacade
 * @Description 线程工厂，异步任务关联opentrace的trace信息
 * @Author zhangyl
 * @Date 2023/8/2 14:15
 */
@Slf4j
public class TracingThreadFactory implements ThreadFactory {
    private final Tracer tracer;

    public TracingThreadFactory() {
        this.tracer = GlobalTracer.get();
    }

    @Override
    public Thread newThread(Runnable r) {
        // 获取当前线程的ActiveSpan
        //Span activeSpan = tracer.activeSpan();
        Span span = tracer.buildSpan("thread-pool-task").start();
        return new Thread(() -> {
            // 在新线程中激活Span
            try (Scope scope = tracer.scopeManager().activate(span)) {
                r.run();
            }catch (Exception e) {
                // 记录异常
                span.log(e.getMessage());
            } finally {
                // 结束Span
                span.finish();
            }
        });


        // 创建新的线程，并封装Runnable以传递Span上下文
        /*return new Thread(() -> {
            // 在新线程中激活Span
            if (activeSpan != null) {
                try (Scope scope = tracer.activateSpan(activeSpan)) {
                    r.run();
                }
            } else {
                r.run();
            }
        });*/
    }
}
